package com.crm.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.crm.base.PageResult;
import com.crm.domain.dto.QueryLogs;
import com.crm.domain.entity.Logs;
import com.crm.domain.vo.LogsVo;
import com.crm.mapper.LogMapper;
import com.crm.service.LogService;

import com.crm.utils.HttpStatus;
import com.crm.utils.ObjectUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;


@Service
@Slf4j
@RequiredArgsConstructor
public class LogServiceImpl extends ServiceImpl<LogMapper, Logs> implements LogService {
    private final LogMapper logMapper;

    /**
     * 查询日志列表
     * @param queryLogs
     * @return
     */
    @Override
    public PageResult<LogsVo> queryLogList(QueryLogs queryLogs) {
        // 设置分页参数
        Page<Logs> page = Page.of(queryLogs.getPageNum(), queryLogs.getPageSize());

        LambdaQueryWrapper<Logs> queryWrapper = Wrappers.<Logs>lambdaQuery()
//                .like(ObjectUtils.isNotEmpty(queryLogs.getKeyword()), Logs::getCreateBy, queryLogs.getKeyword())
                .ge(ObjectUtil.isNotEmpty(queryLogs.getBeginTime()), Logs::getBeginCreateTime, queryLogs.getBeginTime())
                .le(ObjectUtil.isNotEmpty(queryLogs.getEndTime()), Logs::getEndCreateTime, queryLogs.getEndTime());
        // 执行分页查询
        Page<Logs> logsPage = logMapper.selectPage(page, queryWrapper);
        // 结果转换
        List<LogsVo> logsVoList = logsPage.getRecords().stream().map(log -> {
            LogsVo logsVo = new LogsVo();
            BeanUtils.copyProperties(log, logsVo);
            return logsVo;
        }).collect(Collectors.toList());

        // 构建分页响应
        PageResult<LogsVo> pageResult = new PageResult<>();
        pageResult.setTotal(logsVoList.size());
        pageResult.setRows(logsVoList);
        pageResult.setCode(HttpStatus.SUCCESS);
        pageResult.setMsg("查询成功");
        return pageResult;
    }
}
